﻿using System;
using System.Collections.Generic;
using System.Text;
using Acms.Bll;

namespace Acms.DataControls
{
    [System.ComponentModel.Designer(typeof(TemplateHierarchyDataSourceDesigner))]
    [System.Web.UI.ToolboxData("<{0}:TemplateHierarchyDataSource runat=server/>")]
    public class TemplateHierarchyDataSource : GenericDataSource<TemplateHierarchy>
    {
        public enum Fields
        {
            Id,
            ParentId,
            ParentName,
            ChildId,
            ChildName,
            Sequence,
            ConcurencyId
        }

        protected override TemplateHierarchy PopulateData(UpdateAction action, System.Collections.IDictionary keys, System.Collections.IDictionary values, System.Collections.IDictionary oldValues)
        {
            TemplateHierarchy tmp = null;
            object concurencyId = null;
            if (action == UpdateAction.Insert)
            {
                tmp = TemplateHierarchy.CreateInstance();
            }
            else
            {
                int id = GetValue<int>(Fields.Id, keys);
                concurencyId = GetValue<byte[]>(Fields.ConcurencyId, keys);
                tmp = TemplateHierarchy.GetById(id);
            }

            if (tmp != null)
            {
                tmp.CheckConcurent(concurencyId);

                if (RequiresUpdate<int>(Fields.ParentId, values, oldValues))
                {
                    tmp.ParentId = GetValue<int>(Fields.ParentId, values);
                }

                if (RequiresUpdate<int>(Fields.ChildId, values, oldValues))
                {
                    tmp.ChildId = GetValue<int>(Fields.ChildId, values);
                }

                if (RequiresUpdate<int>(Fields.Sequence, values, oldValues))
                {
                    tmp.Sequence = GetValue<int>(Fields.Sequence, values);
                }
            }
            return tmp;
        }

        protected override int SaveChanges(TemplateHierarchy item)
        {
            item.Update();
            return 1;
        }

        protected override int Delete(TemplateHierarchy item)
        {
            item.Delete();
            return 1;
        }

        protected override void AddInsertedKey(TemplateHierarchy item, System.Collections.IDictionary values)
        {
            values[Fields.Id.ToString()] = item.Id;
        }

    }

    public class TemplateHierarchyDataSourceDesigner : GenericDataSourceDesigner<TemplateHierarchy>
    {
        protected override TemplateHierarchy GetDesignTimeItem(int index)
        {
            return TemplateHierarchy.CreateInstance();
        }
    }
}
